package cn.tedu.zx.gateway.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.List;

@Component
@Slf4j
//使用MyFilter类必须实现接口GlobalFilter,
//等于初始化过滤器 然后可以在类里自定义过滤器的内容
//若需定义多个过滤器，则需实现接口Ordered  以设置执行顺序

public class MyFilter01 implements GatewayFilter, Ordered {

 //   在响应的时候,保证和前端对接,不能随意返回字符串,返回的应该是固定格式的对象json;
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();//获取请求对象
        HttpHeaders headers = request.getHeaders();//拿请求头


//所有携带Authorization的头,放行,没携带的,拦截响应认证失败的JJsonResult
        List<String> list1 = headers.get("Authorization");
        ServerHttpResponse response = exchange.getResponse();
        //拿到这个值数据,但是有可能为空
        if (list1==null||list1.size()==0){
//JsonResult 准备 {"status":-999,"message":"您当前未认证","data":null}
            JsonResult jsonResult = new JsonResult();
            jsonResult.setMessage("您当前未认证");
            jsonResult.setData(null);
            String jsonData = "{\"status\":-999,\"message\":\"您当前未认证\",\"data\":null}";
            response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
            return response.writeWith(Mono.fromSupplier(()->{
                return response.bufferFactory().wrap(jsonData.getBytes(StandardCharsets.UTF_8));
            }));
        }else {
            return chain.filter(exchange);//生成一个继续执行过滤器后的功能Mono;

        }



    }

    @Override
    public int getOrder() {
//        设置最小数字  该过滤器最先执行
        return Integer.MIN_VALUE;
    }//设置执行顺序
}
